<template>
  <div class="retention-report-config">
    <a-form-model  labelAlign="right" layout="horizontal" :labelCol="{span: 2, offset: 0}">
      <a-form-model-item label="初始行为">
        <IndicatorGroup
          v-bind:properties="properties"
          v-bind:events="events"
          v-bind:measures="measures"
          v-bind:indicators="config.first_event.indicators"
          v-bind:datasourceId="form.datasourceId"
        ></IndicatorGroup>
      </a-form-model-item>
      <a-form-model-item label="后续行为">
        <IndicatorGroup
          v-bind:properties="properties"
          v-bind:events="events"
          v-bind:measures="measures"
          v-bind:indicators="config.second_event.indicators"
          v-bind:datasourceId="form.datasourceId"
        ></IndicatorGroup>
      </a-form-model-item>
      <a-form-model-item label="分组条件">
        <DimensionGroup v-bind:properties="properties" v-bind:dimensions="config.by_field"></DimensionGroup>
      </a-form-model-item>
      <a-form-model-item label="用户条件">
        <a-button @click="addRule">添加筛选</a-button>
        <MultiLevelFilter ref="filter" v-model="config.user_filter" v-bind:properties="userPropertiesAndGroups" v-on:remove="demote" v-bind:datasourceId="form.datasourceId"></MultiLevelFilter>
      </a-form-model-item>
      <a-form-model-item label="时间">
        <a-range-picker @change="onChange" v-model="defaultTime" :placeholder="['开始时间', '结束时间']" />
        <a-select v-model="form.config.time.unit" @change="changeUnit" style="width: 100px; margin-left: 5px;" placeholder="请选择">
          <a-select-option :value="item.value" v-for="item in timeUnits" :key="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="显示">
        <a-select v-model="form.config.time.duration" @change="changeDuration" style="width: 100px; margin-left: 5px;" placeholder="请选择">
          <a-select-option :value="item.value" v-for="item in timeDuration" :key="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
        <a-input-number 
          v-show="form.config.time.duration == 'custom'"
          ref="customDuration" 
          :max="100" 
          :min="1" 
          v-model="form.config.time.customDuration"
          :formatter="customDurationFormatter"
          :parser="value => value.replace('%', '')" 
          style="width:100px; visibility:visible; margin-left: 5px;"
        >
        </a-input-number>
        <a-select v-model="form.config.config.is_wastage" style="width: 100px; margin-left: 5px;" placeholder="留存/流失">
          <a-select-option :value="item.value" v-for="item in retention" :key="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
  </div>
</template>

<script>
import IndicatorGroup from "./components/IndicatorGroup";
import DimensionGroup from "./components/DimensionGroup";
import DisplayGroup from "@/views/components/DisplayGroup.vue";
import MultiLevelFilter from "@/views/components/Filter/MultiLevelFilter.vue"; // 引入新版级联筛选组件
export default {
  name: "RetentionReportConfig",
  components: {MultiLevelFilter, DimensionGroup, IndicatorGroup, DisplayGroup },
  props: {
    config: Object,
    properties: Array,
    events: Array,
    measures: Array,
    userProperties: Array,
    time: Object,
    form: Object
  },
  data: function() {
    return {
      tree_show: false,
      config_num: 0,
      timeDuration:[],
      customDuration: 1,
      timeUnitSign: '',
      timeUnits: [
        {
            label: '按天',
            value: 'day'
        },
        {
            label: '按周',
            value: 'week'
        },
        {
            label: '按月',
            value: 'month'
        }
      ],
      durationOptions:{
        dayTimeDuration:[
          {
              label: '次日',
              value: 1
          },
          {
              label: '7日',
              value: 7
          },
          {
              label: '14日',
              value: 14
          },
          {
              label: '30日',
              value: 30
          },
          {
              label: '60日',
              value: 60
          },
          {
              label: '自定义',
              value: 'custom'
          }
        ],
        weekDuration:[
          {
              label: '次周',
              value: 1
          },
          {
              label: '8周',
              value: 8
          },
          {
              label: '12周',
              value: 12
          },
          {
              label: '24周',
              value: 24
          },
          {
              label: '自定义',
              value: 'custom'
          }
        ],
        monthDuration:[
          {
              label: '次月',
              value: 1
          },
          {
              label: '6月',
              value: 6
          },
          {
              label: '12月',
              value: 12
          },
          {
              label: '24月',
              value: 24
          },
          {
              label: '自定义',
              value: 'custom'
          }
        ]
      },
      retention: [
        {
          label: '留存',
          value: 0
        },
        {
          label: '流失',
          value: 1
        }
      ],
      defaultTime: null
    };
  },
  computed: {
    userPropertiesAndGroups: function () {
        return this.properties.filter((item) => {
            return item.name.indexOf("users.") === 0 || item.name.indexOf("virtual.users.") === 0;
        });
    },
  },
  created () {
    this.timeDuration = this.durationOptions.dayTimeDuration;
    this.timeUnitSign = "天"
  },
  watch: {}, 
  methods: {
      //条件组降级：如果条件组只剩一个条件，那么移除当前条件组，将剩下的这个条件合并到上级条件组中。
      demote: function (index) {
          let originalFilter = this.config.user_filter;
          let filterIndex = originalFilter.filters.findIndex((item) => {
              return item.index === index;
          });
          if(filterIndex !== -1) {
              let filter = originalFilter.filters[filterIndex];
              originalFilter.filters.splice(filterIndex, 1);
              originalFilter.condition = filter.condition;
              filter.rules.forEach((item, index) => {
                  originalFilter.rules.push(item);
              });
              filter.filters.forEach((item, index) => {
                  originalFilter.filters.push(item);
              });
          }
      },
      changeUnit (dateValue) {
        switch (dateValue){
          case "day":
              this.timeDuration = this.durationOptions.dayTimeDuration;
              this.timeUnitSign = "天";
              break;
          case "week":
              this.timeDuration = this.durationOptions.weekDuration;
              this.timeUnitSign = "周";
              break;
          case "month":
              this.timeDuration = this.durationOptions.monthDuration;
              this.timeUnitSign = "月";
              break;
        }
        this.form.config.time.duration = 1;
        this.form.config.time.customDuration = 1;
        this.changeDuration(1);
      },
      changeDuration (value) {
        if (value !== "custom"){
          this.form.config.time.customDuration = 1;
        }
      },
      customDurationFormatter (value) {
        return value + this.timeUnitSign;
      },
      onChange (e, date) {
        this.form.config.time.start = date[0]
        this.form.config.time.end = date[1]
      },
      addRule() {
        this.$refs.filter.addRule();
      },
      change_all(b, obj) {
        if (b) {
          // 组件消失
          this.config.user_filter = null;
          this.tree_show = false;
        } else {
          // 组件数据更改
          this.config.user_filter = obj;
        }
      },
      show_tree() {
        this.config.user_filter = {
          key: Math.random()
              .toString(36)
              .substr(2),
          Hierarchy: 0, // 逻辑层级
          property: "", // 事件属性名称
          operator: "", // 操作符
          value: "", // 事件属性值
          values: [] // 事件属性值数组
        };
        this.tree_show = true;
      }
  },
  mounted: function() {
    if (this.form.config.time.start || this.form.config.time.end) {
      this.defaultTime = [this.moment(this.form.config.time.start).format('YYYY-MM-DD'), this.moment(this.form.config.time.end).format('YYYY-MM-DD')]
    } else {
      this.defaultTime = null
    }
    // 对树形组件的数据进行标准化处理
    let obj = this.config.user_filter;
    if (obj.condition && obj.rules.length > 1) {
      this.tree_show = true;
    }
    // 对树形组件进行展示，并且更改数据格式
    if (obj.condition && obj.rules.length == 1) {
      this.config.user_filter = {
        key: obj.rules[0].key,
        Hierarchy: 1, // 逻辑层级
        property: obj.rules[0].property, // 事件属性名称
        operator: obj.rules[0].operator, // 操作符
        value: obj.rules[0].value, // 事件属性值
        values: obj.rules[0].values // 事件属性值数组
      };
      this.tree_show = true;
    }
    // 树形组件为空筛选条件
    if (obj.condition && obj.rules.length == 0) {
      this.tree_show = false;
    }
    // 当前树形组件筛选条件为单条
    if (obj && !obj.condition) {
      this.config.user_filter = {
        key: obj.key,
        Hierarchy: obj.Hierarchy, // 逻辑层级
        property: obj.property, // 事件属性名称
        operator: obj.operator, // 操作符
        value: obj.value, // 事件属性值
        values: obj.values // 事件属性值数组
      };
      this.tree_show = true;
    }
  }
};
</script>

<style scoped>
.event-report-config {
  padding: 0px;
  /*margin: 0px;*/
  margin-bottom: 10px;
}

.ant-row.ant-form-item {
  display: flex;
  justify-content: flex-start;
  margin-top: 10px;
}

.retention-report-config >>> .ant-form-item-control-wrapper {
  flex: 1;
}
</style>